package com.study.gamecube.service;

import com.study.gamecube.dao.GameGoodsDao;
import com.study.gamecube.pojo.GameGoods;
import com.study.gamecube.pojo.NewGameGoods;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author peng
 */
@Service
public class GameGoodsService {
    @Autowired
    private GameGoodsDao gameGoodsDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 上架游戏
     *
     * @param gameGoods
     * @return
     */
    @Transactional
    public GameGoods addGoods(GameGoods gameGoods) {
        GameGoods goods = gameGoodsDao.save(gameGoods);
        NewGameGoods newGameGoods = new NewGameGoods();
        newGameGoods.setGameName(gameGoods.getGameName());
        newGameGoods.setId(gameGoods.getId());
        newGameGoods.setVersion(gameGoods.getVersion());
        newGameGoods.setPrice(gameGoods.getPrice().getAmountMajorInt());
        rabbitTemplate.convertAndSend("goods.topic","goods.insert",newGameGoods);
        return goods;
    }

    /**
     * 下架游戏
     *
     * @param id
     */
    public void deleteById(Long id) {
        gameGoodsDao.deleteById(id);
        rabbitTemplate.convertAndSend("goods.topic","goods.delete",id);
    }

    /**
     * 更新游戏信息
     *
     * @param gameGoods
     * @return
     */
    public GameGoods updateGoods(GameGoods gameGoods) {
        GameGoods goods = gameGoodsDao.save(gameGoods);
        rabbitTemplate.convertAndSend("goods.topic","goods.insert",goods);
        return goods;
    }

    /**
     * 查询所有游戏
     *
     * @return
     */
    public List<GameGoods> findAll() {
        return gameGoodsDao.findAll();
    }

    /**
     * 依据ids查找游戏
     *
     * @param ids
     * @return
     */
    public List<GameGoods> findByIds(List<Long> ids) {
        List<GameGoods> goodsList = new ArrayList<GameGoods>(); ;
        for (Long id : ids) {
            GameGoods goods = gameGoodsDao.getById(id);
            goodsList.add(goods);
        }
        return goodsList;
    }
}
